package com.ljd.blog.config;

import com.ljd.blog.interceptor.LoginInterceptor;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import java.io.File;

/**
 * @author ljd
 * @version 1.0
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())
                .addPathPatterns("/admin/**")
                .excludePathPatterns("/admin")
                .excludePathPatterns("/admin/login");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String dirPath = jarF.getParentFile().toString()+"/upload/";

        String os = System.getProperty("os.name");

        System.out.println(os);

        if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
            System.out.println("file:" + dirPath);

        } else {  //linux 和mac
//            registry.addResourceHandler("/upload/**") //虚拟路劲
//                    .addResourceLocations("file:" + System.getProperty("user.dir") + "/upload/");//jar 同级目录
//            System.out.println("file:" + System.getProperty("user.dir") + "/upload/");
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
            System.out.println("file:" + dirPath);
        }
    }
}
